## Civcraft: SC Mod Resource Utilities

import CvUtil
from CvPythonExtensions import *

# globals
gc = CyGlobalContext()

#
# Returns how many resources each unit can harvest from a plot,
# taking into consideration:
# 1.) Base number of resources
# 2.) Distance degradation (distance from collection center) (not implemented)
# 3.) Harvester degradation (every harvester lowers output of plot) (not implemented)
# 4.) The minimum amount each harvester can harvest.
def getResourcesForHarvest(pPlot, iPlayerID):
    pBonusInfo = gc.getBonusInfo(pPlot.getBonusType(-1))

    # Get the base harvest
    iTotalHarvest = pBonusInfo.getResourcesPerHarvest()

    # Modify by the distance from the closest collection center
    iDistanceDegrade = getDistanceFromClosestCollectionCenter(pPlot, iPlayerID) - pBonusInfo.getMinDistanceFromCapital()
    CvUtil.pyAssert(iDistanceDegrade >= 0, "Harvestable Resource found closer to capital than allowed on %d, %d" % (pPlot.getX(), pPlot.getY()))
    iTotalHarvest = iTotalHarvest - (iDistanceDegrade * pBonusInfo.getDistanceDegrade())
    
    # Modify by degrading for each harvester harvesting the plot.
    # Make sure not to actually add the harvest degrade because of "negative" harvesters if the plot is empty
    iTotalHarvesters = max(0, getTotalHarvesters(pPlot))
    iTotalHarvest = iTotalHarvest - (iTotalHarvesters * pBonusInfo.getHarvesterDegrade())

    # If we're below the minimum, just use the minimum
    iMinResources = pBonusInfo.getMinResourcesPerHarvest()
    if (iTotalHarvest < iMinResources):
        iTotalHarvest = iMinResources
    
    return iTotalHarvest

def getDistanceFromClosestCollectionCenter(pPlot, iPlayerID):
    pPlayer = gc.getPlayer(iPlayerID)
    iNumCities = pPlayer.getNumCities()

    iMinDistance = 9999 # To be overwritten.

    # Go through all the player's cities
    for iI in range(0, iNumCities):
        pLoopCity = pPlayer.getCity(iI)
        iDistance = max(abs(pPlot.getX() - pLoopCity.getX()), abs(pPlot.getY() - pLoopCity.getY()))
        # Check any cities less than the currently shortest distance for collection centers
        if (iDistance < iMinDistance):
            for iJ in range(0, gc.getNumBuildingInfos()):
                if (gc.getBuildingInfo(iJ).isCollectionCenter() and pLoopCity.hasBuilding(iJ)):            
                    iMinDistance = iDistance
                    CvUtil.pyPrint("Setting distance on city to %d" % iDistance)
                    break
        

    return iMinDistance

def getTotalHarvesters(pPlot):
    iHarvesters = 0

    for iI in range(0, pPlot.getNumUnits()):
        pLoopUnit = pPlot.getUnit(iI)
        if (pLoopUnit.getGroup().getAutomateType() == AutomateTypes.AUTOMATE_HARVEST):
            iHarvesters += 1

    return iHarvesters


